<script setup lang="ts">
import type { StudentWordItem, StudentWordListRequestParams } from '@/api/types/student'
import type { WordWithStatus } from '@/pages/wordStudy/type'
import { handleApiError } from '@/api'
import { studentApi } from '@/api/modules/student'
import NavBar from '@/components/NavBar/index.vue'
import { WordDegree } from '@/enums/word'
import { useCurrentStudentInfoStore } from '@/stores/modules/useCurrentStudentInfoStore'
import { useUnitStudyWordsStore } from '@/stores/modules/useUnitStudyWordsStore'
import { dialog } from '@/utils/dialog'
import { message } from '@/utils/message'
import { navigateBack } from '@/utils/navigation'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import ExitDialog from './components/ExitDialog.vue'
import HeaderTips from './components/HeaderTips.vue'
import PreCheckWord from './components/PreCheckWord.vue'

interface PreCheckUrlParams extends StudentWordListRequestParams {
  isExperienceCourse: boolean | undefined | string
}

const exitDialogRef = ref()
const targetWordCount = ref(14)
const words = ref<WordWithStatus[]>([])
const unitStudyWordsStore = useUnitStudyWordsStore()
const studentInfoStore = useCurrentStudentInfoStore()

// 单词未达到15个
const WORD_COUNT_LIMIT = 1
// X倍数
const X_MULTIPLE = 1

const urlParams = ref<PreCheckUrlParams>({
  studentId: studentInfoStore.studentId,
  lessonId: studentInfoStore.lessonId,
  courseId: 0,
  unitNo: 1,
  isExperienceCourse: false,
})

const isExperienceCourse = computed(() => {
  return urlParams.value.isExperienceCourse === '1'
})

const selectWordLimit = computed(() => {
  // 限制选择单词数量 ， 体验45个单词 ， 否则999
  return isExperienceCourse.value ? 45 : 999
})

function formatPreCheckRequestParams(params: StudentWordListRequestParams, words: WordWithStatus[]) {
  return {
    studentId: params.studentId,
    courseId: params.courseId,
    unitNo: params.unitNo,
    lessonId: params.lessonId,

    words: words.map(word => ({
      wordId: word.wordId,
      degree: word.known ? WordDegree.KNOWN : WordDegree.UNKNOWN,
    })),
  }
}

async function onConfirm(words: WordWithStatus[]) {
  const params = formatPreCheckRequestParams(urlParams.value, words)

  // 判断已选择的单词是否全部熟词（已选单词=0），提示见 已选单词全部为已会demo 弹窗
  const isAllKnown = words.every(word => word.known === true)
  if (isAllKnown) {
    const [error] = await studentApi.shorthandPreStudy(params)
    if (error) {
      return handleApiError(error)
    }
    // 返回列表
    return dialog.show({
      title: '提示',
      contentTitle: '点个赞 (>﹏<)',
      contentSubTitle: '全部都会啦，不需要再识记啦~',
      buttons: [
        {
          text: '返回',
          type: 'primary',
          onClick: navigateBack,
        },
      ],
    })
  }

  // 是否为体验课
  if (isExperienceCourse.value) {
    // 判断已选择的不会和模糊单词否低于15个单词，若低于并且存在单词未筛选，提示见demo；
    const unknownWords = words.filter(word => word.known === false)
    if (unknownWords.length < WORD_COUNT_LIMIT) {
      return dialog.show({
        title: '提示',
        contentTitle: '选词数量未达到15个',
        contentSubTitle: '再选几个单词吧，凑成5的倍数记忆效果更好',
        buttons: [
          {
            text: '继续选词',
            type: 'primary',
          },
        ],
      })
    }

    // 判断已选择的不会和模糊单词是否是X的倍数，若不是并且存在单词未筛选，提示见demo；
    if (unknownWords.length % X_MULTIPLE !== 0) {
      return dialog.show({
        title: '提示',
        contentTitle: '选词数量建议是5的倍数',
        contentSubTitle: '再选几个单词吧，凑成5的倍数记忆效果更好呢！',
        buttons: [
          {
            text: '继续选词',
            type: 'primary',
          },
        ],
      })
    }
  }
  else {
    // 存在未作答时弹窗提示。 点击我知道了，页面滚动到未作答的题目。
    const unAnsweredWords = words.filter(word => word.known === null)
    if (unAnsweredWords.length > 0) {
      return dialog.show({
        title: '提示',
        contentTitle: '存在单词未作答',
        contentSubTitle: '是否有单词遗漏了，检查看看会不会呢？',
        buttons: [
          {
            text: '继续选词',
            type: 'primary',
          },
        ],
      })
    }
  }

  const [error] = await studentApi.shorthandPreStudy(params)
  if (error) {
    return handleApiError(error)
  }

  unitStudyWordsStore.switchToShorthand()
  unitStudyWordsStore.startStudyWords(urlParams.value)
}

function handleExceed() {
  message.info(`不能超过${selectWordLimit.value}个单词哦，快去识记吧`)
}

function formatWords(words: StudentWordItem[]) {
  return words.map(word => ({
    ...word,
    known: null,
  }))
}

async function loadWords() {
  const [error, data] = await studentApi.getStudentWordList(urlParams.value)
  if (error) {
    return handleApiError(error)
  }
  words.value = formatWords(data.data.words)
}

function handleLeftClick() {
  exitDialogRef.value?.openDialog()
}

onLoad((options: any) => {
  urlParams.value = {
    ...urlParams.value,
    ...options,
  }
  loadWords()
})
</script>

<template>
  <view class="pre-check">
    <NavBar title="学前检查" @left-click="handleLeftClick" />
    <HeaderTips>3秒内不认识的单词，标记为不会，系统将帮助你记忆巩固哦</HeaderTips>

    <ExitDialog ref="exitDialogRef" />
    <PreCheckWord
      :words="words"
      :limit="selectWordLimit"
      :target-count="targetWordCount"
      @on-confirm="onConfirm"
      @on-exceed="handleExceed"
    />
  </view>
</template>

<style lang="scss" scoped>
.pre-check {
  padding-bottom: 120rpx;
}
</style>
